package com.whmskj.xjlhsc.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhsc.entity.Sb02EquipmentCounterAccount;
import com.whmskj.xjlhsc.schedul.async.po.YiqianjiReport;
import com.whmskj.xjlhsc.schedul.async.service.YiqianjiReportService;
import com.whmskj.xjlhsc.service.Sb02EquipmentCounterAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.*;

@SaIgnore
@RestController
@RequestMapping("/api/yiqianjiReport")
public class YiqianjiReportController {

    @Autowired
    private YiqianjiReportService service;

    @Autowired
    private Sb02EquipmentCounterAccountService sb02EquipmentCounterAccountService;

    @GetMapping("/list")
    public AjaxResult list(YiqianjiReport param) {
        return Page.getDataTable(service.findPage(param));
    }

    @GetMapping("/chart1")
    public AjaxResult chart1(YiqianjiReport param) {
        Map<String, List<Sb02EquipmentCounterAccount>> result = sb02EquipmentCounterAccountService.findEquipmentList();
        List<Sb02EquipmentCounterAccount> list = result.get("清花").stream().filter(f-> f.getDevicename().contains("异纤机")).toList();
        List<String> deviceNames = list.stream().map(m-> m.getDevicename() + m.getPlatform()).toList();
        List<String> dateRange = !param.getDateRange().isEmpty() ? param.getDateRange() :
                Arrays.asList(LocalDate.now().minusDays(30).toString(), LocalDate.now().toString());
        List<String> dates = getDate(dateRange);
        List<List<Double>> value = new ArrayList<>();
        param.setDateRange(dateRange);
        List<YiqianjiReport> yiqianjiReportList = service.findList(param);
        deviceNames.forEach(deviceName->{
            List<Double> doubleList = new ArrayList<>();
            dates.forEach(date->{
                double sum = yiqianjiReportList.stream().filter(filter -> deviceName.contains(filter.getDeviceName()) && date.equals(filter.getDateYmd())).mapToDouble(YiqianjiReport::getTotalJet).sum();
                doubleList.add(sum);
            });
            value.add(doubleList);
        });
        Map<String, Object> map = new HashMap<>();
        map.put("xdata", dates);
        map.put("legends", deviceNames);
        map.put("value", value);
        return AjaxResult.success(map);
    }

    private List<String> getDate(List<String> dateRange){
        LocalDate start = LocalDate.parse(dateRange.get(0));
        LocalDate end = LocalDate.parse(dateRange.get(1));
        List<String> dates = new ArrayList<>();
        while(!start.isAfter(end)){
            dates.add(start.toString());
            start = start.plusDays(1);
        }
        return dates;
    }
}
